//
//  MNDSettingViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/10.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDSettingViewController.h"
#import "MNDResetPasswordViewController.h"
#import "SYClearCache.h"
#import "MNDGestureViewController.h"
#import "MNDAboutViewController.h"

#import "UserDefaultsTool.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import <StoreKit/StoreKit.h>

#import <UMPush/UMessage.h>

@interface MNDSettingViewController ()

@property (weak, nonatomic) IBOutlet UISwitch *fingerprintPwdSwitch;

@property (weak, nonatomic) IBOutlet UISwitch *gestureSwitch;
@property (weak, nonatomic) IBOutlet UILabel *totalCacheSize;


@end

@implementation MNDSettingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.totalCacheSize.text = [NSString stringWithFormat:@"%.02fM", [SYClearCache folderSizeAtPath]];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //根据是否有缓存的手势密码设置手势密码的开关状态
    NSString *gesturePassWord = [UserDefaultsTool objectForKey:kGesturePassword];
    if (gesturePassWord.length > 0) {
        self.gestureSwitch.on = YES;
    }else {
        self.gestureSwitch.on = NO;
    }
    
    //根据是否有缓存指纹设置指纹密码的开关状态
    NSString *fingerPassword = [UserDefaultsTool objectForKey:kFingerPassword];
    if (fingerPassword && fingerPassword.length > 0) {
        self.fingerprintPwdSwitch.on = YES;
    }else {
        self.fingerprintPwdSwitch.on = NO;
    }
}

//指纹解锁
- (IBAction)fingerSwitchAction:(UISwitch *)sender {
    NSLog(@"%@",sender);
    if (sender.on == YES) {
        [self evaluateAuthenticate];
    }else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定关闭指纹解锁?" message:nil
                                                                  preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            sender.on = YES;
        }];
        UIAlertAction *closeAction = [UIAlertAction actionWithTitle:@"关闭" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            sender.on = NO;
            [UserDefaultsTool saveObject:nil forKey:kFingerPassword];
            NSString *fingerLock = [UserDefaultsTool objectForKey:kFingerPassword];
            NSLog(@"%@",fingerLock);
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:closeAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    
}

//指纹解锁验证
- (void)evaluateAuthenticate
{
    //iOS8.0后才支持指纹识别接口
    if ([UIDevice currentDevice].systemVersion.floatValue < 8.0) {
        //弹出，该设备不支持指纹解锁
        self.fingerprintPwdSwitch.on = NO;
        [NetworkProgressHUD showHudMsg:@"该设备不支持指纹解锁"];
        return;
    }
    //创建LAContext
    LAContext* context = [[LAContext alloc] init];
//    context
    NSError* error = nil;
    NSString* result = @"通过Home键验证已有手机指纹";
    
    //首先使用canEvaluatePolicy 判断设备支持状态
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error]) {
        //支持指纹验证
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthentication localizedReason:result reply:^(BOOL success, NSError *error) {
            if (success) {
                //验证成功，dismiss密码验证 ，弹出指纹开启成功
                self.fingerprintPwdSwitch.on = YES;
                [NetworkProgressHUD showHudMsg:@"指纹解锁开启成功"];
//                [UserDefaultsTool saveBool:YES forKey:@"fingerSwitchOn"];
                [UserDefaultsTool saveObject:@"YES" forKey:kFingerPassword];
            }
            else
            {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    //其他情况，切换主线程处理
                     self.fingerprintPwdSwitch.on = NO;
                }];
               
                NSLog(@"%@",error.localizedDescription);
                switch (error.code) {
                    case LAErrorSystemCancel:
                    {
                        //系统取消授权，如其他APP切入
                        break;
                    }
                    case LAErrorUserCancel:
                    {
                        //用户取消验证Touch ID
                        break;
                    }
                    case LAErrorAuthenticationFailed:
                    {
                        //授权失败 ，弹出验证失败
                        [NetworkProgressHUD showHudMsg:@"验证失败"];
                        break;
                    }
                    case LAErrorPasscodeNotSet:
                    {
                        //系统未设置密码
                        break;
                    }
                    case LAErrorTouchIDNotAvailable:
                    {
                        //设备Touch ID不可用，例如未打开
                        [NetworkProgressHUD showHudMsg:@"设备未开启指纹功能"];
                        break;
                    }
                    case LAErrorTouchIDNotEnrolled:
                    {
                        //设备Touch ID不可用，用户未录入
                        [NetworkProgressHUD showHudMsg:@"Touch ID不可用"];
                        break;
                    }
                    case LAErrorUserFallback:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //用户选择输入密码，切换主线程处理
                            
                        }];
                        break;
                    }
                    default:
                    {
                        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                            //其他情况，切换主线程处理
                        }];
                        break;
                    }
                }
            }
        }];
    }
    else
    {
        //不支持指纹识别，LOG出错误详情
//        NSLog(@"不支持指纹识别");
//        self.fingerprintPwdSwitch.on = NO;
//        [NetworkProgressHUD showHudMsg:@"设备不支持指纹识别"];
        
        switch (error.code) {
            case LAErrorTouchIDNotEnrolled:
            {
                NSLog(@"TouchID is not enrolled");
                break;
            }
            case LAErrorPasscodeNotSet:
            {
                NSLog(@"A passcode has not been set");
                break;
            }
            default:
            {
                //指纹密码错误5次后被禁用
                NSLog(@"TouchID not available");
                break;
            }
        }
        NSLog(@"%@",error.localizedDescription);
    }
}


//手势密码
- (IBAction)gestureSwitchAction:(UISwitch *)sender {
    if (sender.on == YES) {//开启手势
        [self gotoGestureVC];
    }else {//关闭手势
        [self gotoColseGesture];
    }
}

- (void)gotoGestureVC {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Gesture" bundle:nil];
    MNDGestureViewController *gestureViewcontroller = [storyBoard instantiateViewControllerWithIdentifier:@"MNDGestureViewController"];
    gestureViewcontroller.view.backgroundColor = [UIColor whiteColor];
    gestureViewcontroller.tipLabel.text = @"请设置手势密码";
    gestureViewcontroller.isCloseGesture = NO;;
    gestureViewcontroller.navigationController.navigationBarHidden = NO;
    [self.navigationController pushViewController:gestureViewcontroller animated:YES];
}

- (void)gotoColseGesture {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Gesture" bundle:nil];
    MNDGestureViewController *gestureViewcontroller = [storyBoard instantiateViewControllerWithIdentifier:@"MNDGestureViewController"];
    gestureViewcontroller.view.backgroundColor = [UIColor whiteColor];
    gestureViewcontroller.tipLabel.text = @"请输入原手势密码";
    gestureViewcontroller.topGestureView.hidden = YES;
    gestureViewcontroller.topLogImgV.hidden = NO;
    gestureViewcontroller.isCloseGesture = YES;
    gestureViewcontroller.forgetGestureButton.hidden = NO;
    [self.navigationController pushViewController:gestureViewcontroller animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0 && indexPath.row == 0) {
        [self performSegueWithIdentifier:[MNDResetPasswordViewController description] sender:nil];
    }
    
    if (indexPath.section == 1 && indexPath.row == 1) {
        
        WeakSelf(self);
        [SYClearCache cleanCache:^{
            [NetworkProgressHUD showHudMsg:@"清理成功"];
            
            weakself.totalCacheSize.text = [NSString stringWithFormat:@"%.02fM", [SYClearCache folderSizeAtPath]];
        }];
    }
    
    if (indexPath.section == 1 && indexPath.row == 0) {
        [self performSegueWithIdentifier:[MNDAboutViewController description] sender:nil];
    }
    
    if (indexPath.section == 1 && indexPath.row == 2) {
        //AppStore评分
        if ([SKStoreReviewController respondsToSelector:@selector(requestReview)]){
            [SKStoreReviewController requestReview];
        } else {
            NSString  * nsStringToOpen = [NSString  stringWithFormat: @"itms-apps://itunes.apple.com/app/id%@?action=write-review",@"1072685010"];//替换为对应的APPID
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:nsStringToOpen]];
        }
//        NSString *itunesStr = @"itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=1072685010&pageNumber=0&sortOrdering=2&mt=8";
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:itunesStr]];
    }
}

- (IBAction)logoutAction:(id)sender {

    [NetworkProgressHUD showHud];
    
    WeakSelf(self);
    
    [APIManager sendRequestWithPath:API_USER_LOGOUT parameters:[MNDSign signedParam] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD hideHud];
            [weakself clearUserContents];
            
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"退出失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)clearUserContents {
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    //删除消息推送设置的别名
    [UMessage removeAlias: user.user_code type:@"minidai" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"删除别名失败: %@", error);
        } else {
            NSLog(@"删除别名成功: %@", responseObject);
        }
    }];
    //清除用户数据

    [MNDLoginUserModel deleteAllUserDatas];
    [UserDefaultsTool removeForKey:kOpenDepositAlert];
    //清空手势密码
    [UserDefaultsTool removeForKey:kGesturePassword];
    //清空手势错误次数
    [UserDefaultsTool removeForKey:kErrorCount];
    //关闭手势密码
    [UserDefaultsTool removeForKey:kFingerPassword];
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"clearPomeCircleData" object:nil];
    [APIManager setGeneralHeaderValue:nil forField:@"USERCODE"];
    
    [self clearWebViewCookies];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)clearWebViewCookies {
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    //缓存web清除
    //    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
